package edu.cth.scrabbit.server.core.network;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import edu.cth.scrabbit.shared.network.Statement;

/**
 * A class that creates a thread for each player
 * @author Anders Jonsson, Marcus Harryson
 *
 */
public class PlayerThread extends Thread {

	private Socket serverSocket;

	private ObjectInputStream in;
	private ObjectOutputStream out;
	
	/**
	 * PlayerThread-constructor
	 * @param serverSocket
	 */
	public PlayerThread(Socket serverSocket) {
		this.serverSocket = serverSocket;
	}

	@Override
	public void run() {
		try {
			// initialize out- and input streams
			out = new ObjectOutputStream(serverSocket.getOutputStream());

			in = new ObjectInputStream(serverSocket.getInputStream());

			Statement inStatement = null;
			
			while ((inStatement = (Statement) in.readObject()) != null) {
				Statement outStatement = ServerProtocol.processStatement(
						inStatement, this);
				out.writeObject(outStatement);
				out.flush();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
